package com.opencee.common.utils;

import org.hibernate.validator.HibernateValidator;
import org.springframework.validation.BindException;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Set;

/**
 * hibernate-validator校验工具类
 *
 * @author yadu
 */
public class ValidatorUtil {
    private static Validator validator;

    static {
        validator = Validation.byProvider(HibernateValidator.class)
                .configure()
                // 快速失败，不必每一个约束都校验
                .failFast(true)
                .buildValidatorFactory()
                .getValidator();
    }

    /**
     * 校验对象
     *
     * @param object 待校验对象
     * @param groups 待校验的组
     * @throws BindException 校验不通过，
     */
    public static void validateEntity(Object object, Class<?>... groups)
            throws BindException {
        Set<ConstraintViolation<Object>> constraintViolations = validator.validate(object, groups);
        if (!constraintViolations.isEmpty()) {
            throw new ConstraintViolationException(constraintViolations);
        }
    }
}
